package com.kinon.ceshiaccount.sunmi.print;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.kinon.ceshiaccount.bean.TotalTypeBean;
import com.kinon.ceshiaccount.sunmi.bean.TableBean;
import com.kinon.ceshiaccount.sunmi.bean.TableItem;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.util.SysTimeManage;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import woyou.aidlservice.jiuiv5.ICallback;
import woyou.aidlservice.jiuiv5.IWoyouService;


public class AidlUtil {
    private static final String SERVICE＿PACKAGE = "woyou.aidlservice.jiuiv5";
    private static final String SERVICE＿ACTION = "woyou.aidlservice.jiuiv5.IWoyouService";
    private static int printLength = 0;
    private static String test[] = {"商品", "数量", "价格"};
    private static int width[] = {2, 1, 1};
    private static int alignment[] = {0, 1, 2};
    private static AidlUtil mAidlUtil = null;
    private IWoyouService woyouService;
    private Context context;
    private ServiceConnection connService = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            woyouService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            woyouService = IWoyouService.Stub.asInterface(service);
        }
    };
    /**
     * 设置打印浓度
     */
    private int[] darkness = new int[]{0x0600, 0x0500, 0x0400, 0x0300, 0x0200, 0x0100, 0,
            0xffff, 0xfeff, 0xfdff, 0xfcff, 0xfbff, 0xfaff};

    private AidlUtil() {
    }

    public static AidlUtil getInstance() {
        if (mAidlUtil == null) {
            mAidlUtil = new AidlUtil();
        }
        return mAidlUtil;
    }

    /**
     * 连接服务
     *
     * @param context context
     */
    public void connectPrinterService(Context context) {
        this.context = context.getApplicationContext();
        Intent intent = new Intent();
        intent.setPackage(SERVICE＿PACKAGE);
        intent.setAction(SERVICE＿ACTION);
        context.getApplicationContext().startService(intent);
        context.getApplicationContext().bindService(intent, connService, Context.BIND_AUTO_CREATE);

    }

    /**
     * 断开服务
     *
     * @param context context
     */
    public void disconnectPrinterService(Context context) {
        if (woyouService != null) {
            context.getApplicationContext().unbindService(connService);
            woyouService = null;
        }
    }

    public boolean isConnect() {
        return woyouService != null;
    }

    public ICallback generateCB(final PrinterCallback printerCallback) {
        return new ICallback.Stub() {
            @Override
            public void onRunResult(boolean isSuccess, int code, String msg) throws RemoteException {

            }

        };
    }

    public void setDarkness(int index) {
        if (woyouService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return;
        }

        int k = darkness[index];
        try {
            woyouService.sendRAWData(ESCUtil.setPrinterDarkness(k), null);
            woyouService.printerSelfChecking(null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 取得打印机系统信息，放在list中
     *
     * @return list
     */
    public List<String> getPrinterInfo() {
        if (woyouService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return null;
        }

        List<String> info = new ArrayList<>();
        try {
            info.add(woyouService.getPrinterSerialNo());
            info.add(woyouService.getPrinterModal());
            info.add(woyouService.getPrinterVersion());
            info.add(woyouService.getPrintedLength() + "");
            info.add("");
            //info.add(woyouService.getServiceVersion());
            PackageManager packageManager = context.getPackageManager();
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(SERVICE＿PACKAGE, 0);
                if (packageInfo != null) {
                    info.add(packageInfo.versionName);
                    info.add(packageInfo.versionCode + "");
                } else {
                    info.add("");
                    info.add("");
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }

        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return info;
    }

    /**
     * 初始化打印机
     */
    public void initPrinter() {
        if (woyouService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return;
        }

        try {
            woyouService.printerInit(null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印二维码
     */
    public void printQr(String data, int modulesize, int errorlevel) {
        if (woyouService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return;
        }


        try {
            woyouService.setAlignment(1, null);
            woyouService.printQRCode(data, modulesize, errorlevel, null);
            woyouService.lineWrap(3, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印条形码
     */
    public void printBarCode(String data, int symbology, int height, int width, int textposition) {
        if (woyouService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return;
        }


        try {
            woyouService.printBarCode(data, symbology, height, width, textposition, null);
            woyouService.lineWrap(3, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印文字
     */
    public void printText(String content, float size, boolean isBold, boolean isUnderLine) {
        if (woyouService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return;
        }

        try {
            if (isBold) {
                woyouService.sendRAWData(ESCUtil.boldOn(), null);
            } else {
                woyouService.sendRAWData(ESCUtil.boldOff(), null);
            }

            if (isUnderLine) {
                woyouService.sendRAWData(ESCUtil.underlineWithOneDotWidthOn(), null);
            } else {
                woyouService.sendRAWData(ESCUtil.underlineOff(), null);
            }

            woyouService.printTextWithFont(content, null, size, null);
            woyouService.lineWrap(3, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void getPrintLength() {
        try {
            printLength = woyouService.getPrinterBBMDistance();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private String setNum() {
        String s = "";
        if (printLength == 0) {
            getPrintLength();
        }
        for (int i = 0; i < printLength; i++) {
            s += "*";
        }
        return s;
    }

    public void myPrint(LinkedList<TableBean> list, int amount,
                        String total, String orderno, String take_time,
                        String name, String phone, String dayno) {

        if (woyouService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return;
        }
        try {
            woyouService.printerInit(null);
//            woyouService.sendRAWData(ESCUtil.boldHt(), null);
            woyouService.setAlignment(1, null);
            woyouService.printText("智慧食堂\n", null);
            woyouService.printText("*****************************************" + "\n", null);
            woyouService.sendRAWData(ESCUtil.alignLeft(), null);
            woyouService.printColumnsString(test, width, alignment, null);
            woyouService.setFontSize(40.0f, null);

            for (TableBean tableItem : list) {
                woyouService.printColumnsString(tableItem.getText(),
                        width, alignment, null);
            }

//            for(int i=0;i<3;i++){
//                woyouService.printColumnsString(adb,width,alignment,null);
//            }
            woyouService.setFontSize(24.0f, null);
            String str = "数量:" + amount + "\t\t" + "总价:" + total + "元" + "\n" +
                    "订单编号:" + orderno + "\n" +
                    "取餐时间:" + take_time + "\n" +
                    "姓名:" + name + "\n" +
                    "联系电话:" + phone + "\n";
            woyouService.printText(str, null);
            woyouService.setFontSize(40.0f, null);
            woyouService.printText("取餐编号:" + dayno + "\n", null);
            woyouService.setAlignment(1, null);
            woyouService.setFontSize(24.0f, null);
            woyouService.printText("*****************************************" + "\n", null);
            woyouService.printText("请妥善保管好购物凭证\n", null);
            woyouService.printText("谢谢惠顾!\n", null);
            woyouService.lineWrap(3, null);
            woyouService.cutPaper(null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }


    }

    public void printTotalPrice(ArrayList<TotalTypeBean> list, int total, String totalPrice) {
        if (woyouService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return;
        }
        try {
            woyouService.printerInit(null);
//            woyouService.sendRAWData(ESCUtil.boldHt(), null);
            woyouService.setAlignment(1, null);
            woyouService.printText("智慧食堂\n", null);
            woyouService.printText("***********************************************" + "\n", null);
//            woyouService.sendRAWData(ESCUtil.alignLeft(), null);
//            woyouService.printColumnsString(test,width,alignment,null);
//            woyouService.setFontSize(40.0f,null);
//
//            for (TableBean tableItem : list) {
//                woyouService.printColumnsString(tableItem.getText(),
//                        width, alignment, null);
//            }
            StringBuffer type = new StringBuffer();
            for (TotalTypeBean b : list) {

                type.append("\n\t" + b.getName() + ":" + b.getTotal() + b.getUnit());
            }
            woyouService.setAlignment(0, null);
            woyouService.setFontSize(30.0f, null);
//            String str="数量:"+amount+"\t\t"+"总价:"+total+"元"+"\n"+
//                    "订单编号:"+orderno+"\n"+
//                    "取餐时间:"+take_time+"\n"+
//                    "姓名:"+name+"\n"+
//                    "联系电话:"+phone+"\n";
            String data = SysTimeManage.getInstage().getDate(System.currentTimeMillis());
            String account = SPManage.getInstance().getString("loginaccoun");
            String str = "\t日期:" + data +
                    "\n\t账号:" + account +
                    type.toString() +
                    "\n\t总订单数:" + total +
                    "\n\t总金额:" + totalPrice + "元\n\n";
            woyouService.printText(str, null);
//            woyouService.setFontSize(40.0f,null);
//            woyouService.printText("取餐编号:"+dayno+"\n",null);
            woyouService.setAlignment(1, null);
            woyouService.setFontSize(24.0f, null);
            woyouService.printText("***********************************************" + "\n", null);
//            woyouService.printText("请妥善保管好购物凭证\n",null);
//            woyouService.printText("谢谢惠顾!\n",null);
            woyouService.lineWrap(3, null);
            woyouService.cutPaper(null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void prinTextWithFont(String content) {
        try {
            woyouService.printTextWithFont(content, null, 1.0f, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /*
    *打印图片
     */
    public void printBitmap(Bitmap bitmap) {
        if (woyouService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return;
        }

        try {
            woyouService.setAlignment(1, null);
            woyouService.printBitmap(bitmap, null);
            woyouService.lineWrap(3, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印表格
     */
    public void printTable(LinkedList<TableItem> list) {
        if (woyouService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return;
        }

        try {
            for (TableItem tableItem : list) {
                Log.i("kaltin", "printTable: " + tableItem.getText()[0] + tableItem.getText()[1] + tableItem.getText()[2]);
                woyouService.printColumnsText(tableItem.getText(), tableItem.getWidth(), tableItem.getAlign(), null);
            }
            woyouService.lineWrap(3, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /*
    * 空打三行！
     */
    public void print3Line() {
        if (woyouService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return;
        }

        try {
            woyouService.lineWrap(3, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    public void sendRawData(byte[] data) {
        if (woyouService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return;
        }

        try {
            woyouService.sendRAWData(data, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置T1mini显示内容
     */
    public void setMiniT1ShowData(String data) {
        try {
            if (woyouService != null) {
                woyouService.sendLCDString(data, null);
            }

        } catch (RemoteException e) {
            e.printStackTrace();
        }
//        woyouService.send
    }

    /**
     * 设置T1mini显示图片
     */
    public void setMiniT1Img(Bitmap bitmap) {
        try {
            if (woyouService != null) {
                woyouService.sendLCDBitmap(bitmap, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param flag 1 初始化 2 唤醒LCD 3休眠LCD 4清屏
     */
    public void setLCDCommand(int flag) {
        try {
            if (woyouService != null) {
                woyouService.sendLCDCommand(flag);
            }

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
